package com.bookbuf.social.share.content.media.image.converter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.bookbuf.social.share.content.media.image.util.BitmapUtils;
import com.bookbuf.social.share.content.media.image.util.ImageFormat;
import com.bookbuf.social.share.content.media.image.util.Util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by robert on 16/7/4.
 */
public class FileConverter extends ConfiguredConverter {

	private File file;

	public FileConverter (File file) {
		this.file = file;
	}

	public File asFile () {
		return this.file;
	}

	public String asUrl () {
		return null;
	}

	public byte[] asBinary () {
		return this.getByteArrayWithFormatCheck (this.file);
	}

	public Bitmap asBitmap () {
		BitmapFactory.Options var1 = new BitmapFactory.Options ();
		var1.inJustDecodeBounds = true;
		BitmapFactory.decodeFile (this.file.toString (), var1);
		var1.inSampleSize = BitmapUtils.calculateInSampleSize (var1, BitmapUtils.MAX_WIDTH, BitmapUtils.MAX_HEIGHT);
		var1.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile (this.file.getAbsolutePath (), var1);
	}

	private byte[] getByteArrayWithFormatCheck (File file) {
		if (file != null && file.getAbsoluteFile ().exists ()) {
			byte[] byteArray = getByteArray (file);
			if (byteArray != null && byteArray.length > 0) {
				String checkFormat = ImageFormat.checkFormat (byteArray);
				return ImageFormat.FORMAT_NAMES[1].equals (checkFormat) ? byteArray : Util.compressBytes (byteArray);
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	private static byte[] getByteArray (File file) {
		FileInputStream inputStream = null;
		ByteArrayOutputStream outputStream = null;

		try {
			inputStream = new FileInputStream (file);
			outputStream = new ByteArrayOutputStream ();
			byte[] buffer = new byte[4096];

			int byteCounts;
			while ((byteCounts = inputStream.read (buffer)) != -1) {
				outputStream.write (buffer, 0, byteCounts);
			}
			return outputStream.toByteArray ();
		} catch (Exception e) {
			e.printStackTrace ();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close ();
				}
				if (outputStream != null) {
					outputStream.close ();
				}
			} catch (IOException e) {
				e.printStackTrace ();
			}

		}
		return null;
	}
}
